﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.CSharp;
using MedicalManagementSystem.Models;
using MedicalManagementSystem.Utils;
using MedicalManagementSystem.Helpers;

namespace MedicalManagementSystem.Controllers
{
    public class PatientChartController : GenericController
    {
        //
        // GET: /PatientChart/
        [EnumAuthorize(Roles = UserRoles.DoctorRole | UserRoles.AdminRole)]
        public ActionResult Index(int id)
        {
            return View(PatientChart.GetByPK(id));
        }

        //
        // GET: /PatientChart/Details/5
        [EnumAuthorize(Roles = UserRoles.DoctorRole | UserRoles.AdminRole)]
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /PatientChart/Create
        [EnumAuthorize(Roles = UserRoles.DoctorRole | UserRoles.AdminRole)]
        public ActionResult Create(int? patientId)
        {
            Menu.ID = "patient,createChart";
            var chart = new PatientChart();
            if (patientId.HasValue)
            {
                chart.Patient = Patient.GetByPK(patientId.Value);
            }
            return View(chart);
        }

        [HttpGet]
        public ActionResult CloseChart(int id)
        {
            return View(PatientChart.GetByPK(id));
        }

        [HttpPost]
        public ActionResult CloseChart(PatientChart chat, int? hospitalId)
        {
            var original = PatientChart.GetByPK(chat.id);
            
            if (hospitalId.HasValue)
            {
                original.Hospital = Hospital.GetByPK(hospitalId.Value);
            }
            original.DateLeave = chat.DateLeave;
            original.ChartDestination = chat.ChartDestination;

            try
            {
                DbContext.Instance.PatientChart.ApplyCurrentValues(original);
                DbContext.Instance.SaveChanges();
                return RedirectToAction("Index", "Patient");
            }
            catch (RuleViolationException ruleException)
            {
                ClearModelStateErrors();
                AddViolataionsToModelState(ruleException.Violations);
            }
            return View(original);
        }

        //
        // POST: /PatientChart/Create
        [EnumAuthorize(Roles = UserRoles.DoctorRole | UserRoles.AdminRole)]
        [HttpPost]
        public ActionResult Create(FormCollection collection, int? patientId, int doctorId)
        {
            var patientChart = new PatientChart();
            patientChart.Patient = patientId.HasValue ? Patient.GetByPK(patientId.Value) : null;
            patientChart.Doctor = Doctor.GetByPK(doctorId);
            try
            {
                UpdateModel(patientChart);
                DbContext.Instance.AddToPatientChart(patientChart);
                DbContext.Instance.SaveChanges();
                return RedirectToAction("Index", new{ patientChart.id });
            }
            catch (Exception e)
            {
                ClearModelStateErrors();
                AddViolataionsToModelState(patientChart.GetRuleViolations());
            }
            return View(patientChart);
        }

        //
        // GET: /PatientChart/Edit/5
        [EnumAuthorize(Roles = UserRoles.DoctorRole | UserRoles.AdminRole)]
        public ActionResult Edit(int id)
        {
            var patientChart = PatientChart.GetByPK(id);
            if (patientChart == null)
                return new HttpNotFoundResult(string.Format("Карта {0} не найдена.", id));
            return View(patientChart);
        }

        [EnumAuthorize(Roles = UserRoles.DoctorRole | UserRoles.AdminRole)]
        public ActionResult EditInfo(int id)
        {
            return View(PatientChart.GetByPK(id));
        }


        [AcceptVerbs(HttpVerbs.Post)]
        [EnumAuthorize(Roles = UserRoles.DoctorRole | UserRoles.AdminRole)]
        public ActionResult EditInfo(PatientChart patientChart, int doctorId)
        {
            var original = PatientChart.GetByPK(patientChart.id);
            try
            {
                original.Doctor = Doctor.GetByPK(doctorId);
                DbContext.Instance.PatientChart.ApplyCurrentValues(patientChart);
                DbContext.Instance.SaveChanges();
                return RedirectToAction("Index", new {original.id});
            }
            catch (RuleViolationException ruleException)
            {
                ClearModelStateErrors();
                AddViolataionsToModelState(ruleException.Violations);
            }
            return View(original);
        }

        //
        // POST: /PatientChart/Edit/5

        public class PatientChartModel
        {
            public int id { get; set; }
            public List<DiseaseNote> DiseaseNotes { get; set; }
        }

        [HttpPost]
        public JsonResult Edit(PatientChartModel patientChartModel)
        {
            try
            {
                var chartModel = PatientChart.GetByPK(patientChartModel.id);
                chartModel.DiseaseNotes.Load();
                chartModel.DiseaseNotes.Select(dn => dn.id).ToList().ForEach(id =>
                    DbContext.Instance.DeleteObject(DiseaseNote.GetByPK(id)));
                chartModel.DiseaseNotes.Clear();
                patientChartModel.DiseaseNotes.Each(diseaseNote =>
                                                        {
                                                            DbContext.Instance.AddToDiseaseNote(diseaseNote);
                                                            diseaseNote.PatientChart = chartModel;
                                                        });
                DbContext.Instance.SaveChanges();
                return Json(new { Successed = true });
            }
            catch (RuleViolationException e)
            {
                return Json(new
                {
                    Successed = false,
                    Errors = patientChartModel.DiseaseNotes
                    .SelectMany(pch => pch.GetRuleViolations().Select(r => r.ErrorMessage))
                });
            }
        }

        //
        // GET: /PatientChart/Delete/5
        [EnumAuthorize(Roles = UserRoles.DoctorRole | UserRoles.AdminRole)]
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /PatientChart/Delete/5
        [EnumAuthorize(Roles = UserRoles.DoctorRole | UserRoles.AdminRole)]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
